/**
    Copyright (c) 2010 ATTi 
    All rights reserved.
    Author: Michael Shu
    Purpose : 1. update the Region Code to OOR for the Local OOR Accounts. 
              2. set CMR Group Id (by mbakkemo)
    Date: 5/28/2010
*/


trigger AccountCMRTrigger on Account (before insert, before update)
{
	ID LocalOORRecordTypeID = RecordTypeHelper.GetRecordTypeIdByDevName('Account', 'Local_Advertiser'); 
	if(trigger.isInsert){
	    Integer max = 0;
	    ID CMRGroupRecordTypeID = RecordTypeHelper.GetRecordTypeID('Account', 'CMR Group');
	    
	    try
	    {
	        for (account a : Trigger.new)
	        {
	            if (a.RecordTypeId == CMRGroupRecordTypeID)
	            {
	                if (max == 0)
	                {
	                    max = CMRGroupIdHandler.getMaxCMRId() + 1;
	                }
	                else
	                {
	                    max = max+1;
	                }    
	                a.CMR_Group_ID__c = string.valueof(max);
	            }
	        }
	    }
	    catch (Exception e)
	    {
	        String emsg = 'Account CMR Trigger exception: ' + e.getMessage();
	        System.debug(Logginglevel.ERROR, emsg);
	    }
	    
	    for(Account a : Trigger.new){
	    	if(a.RecordTypeId == LocalOORRecordTypeID){
	    		a.CSS_CustomerRegionCode__c = 'OOR';
	    	}
	    }
	}else if(trigger.isUpdate){
		for(Account a : Trigger.new){
	    	if(a.RecordTypeId == LocalOORRecordTypeID){
	    		a.CSS_CustomerRegionCode__c = 'OOR';
	    	}
	    }
	}
}